from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
import logging, random
from django_redis import get_redis_connection
# from yuntongxun.sms import CCP
from rest_framework import status
from rest_framework.throttling import AnonRateThrottle

from . import constants
from celery_tasks.sms.tasks import send_sms_code


# Create your views here.
logger = logging.getLogger('django')




class SMSCodeView(APIView):
    """发送短信验证码"""
    # throttle_classes = (AnonRateThrottle,)

    def get(self, request, mobile):
        """
        GET /sms_codes/(?P<mobile>1[3-9]\d{9})/
        """
        # 创建连接到redis的对象
        redis_conn = get_redis_connection('verify_codes')
        # # 先判断用户在60s内是否重复发送短信
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            # 如果send_flag有值, 说明60s内重复发发送短信
            return Response({'message': '频繁发送短信'}, status=status.HTTP_400_BAD_REQUEST)

        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)

        # 创建redis的管道
        pl = redis_conn.pipeline()

        # 存储短信验证码到redis
        # redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)

        # 在redis中添加一个发送短信的标记(值)
        # redis_conn.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)

        # 注意:一定要记得执行execute
        pl.execute()

        # 使用容联云通讯发送短信验证码
        # CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES // 60], 1)
        # 使用异步任务发送短信验证码
        send_sms_code.delay(mobile, sms_code)  # 一定要注意调用delay方法才会触发celery的异步任务

        return Response({'message': 'ok'})